package jdbc03;

import java.sql.*;

/**
 * 工具类中要包含:
 * 注册驱动
 * 获取连接
 * 释放资源
 */

public class JDBCUtils {
    /*私有构造方法 不可以在类外创建对象*/
    private JDBCUtils() {

    }

    /*数据库驱动常量*/
    private static final String DRIVER = "com.mysql.jdbc.Driver";
    /*数据库连接URL常量*/
    private static final String URL = "jdbc:mysql://localhost:3306/test02?useSSL=false&characterEncoding=UTF-8";
    /*数据库登录用户名常量*/
    private static final String USER = "root";
    /*数据库登录密码常量*/
    private static final String PASSWORD = "root";


    /*注册驱动,当JDBCUtils类加载的时候,会执行静态代码块,此时会注册驱动*/
    static{
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    /*获取连接的静态方法*/
    public static Connection getConnection(){
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(URL, USER, PASSWORD);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return conn;
    }

    /*释放资源*/
    public static void release(Connection con, Statement statement, ResultSet rs) {
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
